package cn.itcast.p2p20.adapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/23.
 */
public class PicAdapter extends PagerAdapter {

    public int img_res_ids[];

    public PicAdapter(int[] img_res_ids) {
        this.img_res_ids = img_res_ids;
    }

    private List<ImageView> cache = new ArrayList<>(1);

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        if (cache.isEmpty()) {

            ImageView imageView = new ImageView(container.getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            cache.add(imageView);
        }
        ImageView imageView = cache.remove(0);
        container.addView(imageView);

        imageView.setImageResource(img_res_ids[position]);

        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        cache.add((ImageView) object);
        container.removeView((View) object);
    }

    @Override
    public int getCount() {

        return img_res_ids == null ? 0 : img_res_ids.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
